package global

import (
	"flag"
	"fmt"
	"gitee.com/gopher2011/godemo/config"
	"gitee.com/gopher2011/godemo/server/dao"
	"io"
	"os"
	"strings"
	"sync"
	"time"
)

// 静态资源托管地址
const (
	DefaultCDNHttp  = "http://test.static.studygolang.com/"
	DefaultCDNHttps = "https://static.studygolang.com/"
)

const (
	DEV  = "dev"
	TEST = "test"
	PRO  = "pro"
)

var (
	Build       string
	App         = &app{}
	showVersion = flag.Bool("version", false, "打印当前项目的版本")
)

var (
	AuthorityChan   = make(chan struct{}, 1)
	RoleChan        = make(chan struct{}, 1)
	RoleAuthChan    = make(chan struct{}, 1)
	UserSettingChan = make(chan struct{}, 1)
	TopicNodeChan   = make(chan struct{}, 1)
)

type app struct {
	Name      string
	Build     string
	Version   string
	Date      time.Time
	Copyright string //版权信息
	//启动时间
	LaunchTime time.Time
	Uptime     time.Duration

	Env     string
	Host    string
	Port    string
	BaseURL string

	//CDN 资源域名
	CDNHttp  string
	CDNHttps string
	Domain   string
	mu       sync.Mutex
}

func init() {
	App.Name = os.Args[0]
	App.Version = "V4.0.0"
	App.Build = Build
	App.LaunchTime = time.Now()

	file, err := os.Stat(os.Args[0])
	if err != nil {
		panic(err)
	}

	App.Date = file.ModTime() //修改时间

	App.Env = config.Config.MustValue("global", "env")

	App.CDNHttp = config.Config.MustValue("qiniu", "http_domain", DefaultCDNHttp)
	App.CDNHttps = config.Config.MustValue("qiniu", "https_domain", DefaultCDNHttps)
}

func (p *app) Init(domain string) {
	p.Domain = config.Config.MustValue("global", "domain", domain)
}

func (p *app) SetUptime() {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.Uptime = time.Now().Sub(p.LaunchTime)
}

func (p *app) SetCopyright() {
	currentYear := time.Now().Year()
	p.mu.Lock()
	defer p.mu.Unlock()
	one := dao.Website()
	if currentYear == one.StartYear {
		p.Copyright = fmt.Sprintf("%d %s", one.StartYear, one.Domain)
	} else {
		p.Copyright = fmt.Sprintf("%d-%d %s", one.StartYear, currentYear, one.Domain)
	}
}

// 规范的CDN
func (p *app) CanonicalCDN(isHTTPS bool) string {
	cdnDomain := p.CDNHttp
	if isHTTPS {
		cdnDomain = p.CDNHttps
	}
	if !strings.HasSuffix(cdnDomain, "/") {
		cdnDomain += "/"
	}
	return cdnDomain
}

func PrintVersion(w io.Writer) {
	if !flag.Parsed() {
		flag.Parse()
	}
	if showVersion == nil || !*showVersion {
		return
	}
	fmt.Fprintf(w, "Binary: %s\n", App.Name)
	fmt.Fprintf(w, "Version: %s\n", App.Version)
	fmt.Fprintf(w, "Build: %s\n", App.Build)
	fmt.Fprintf(w, "Compile date: %s\n", App.Date.Format("2006-01-02 15:04:05"))
	fmt.Fprintf(w, "Env: %s\n", App.Env)
	os.Exit(0)
}

func OnlineEnv() bool {
	return App.Env == PRO
}
